import 'package:flutter/material.dart';
import 'add_page.dart';
import 'login_page.dart';
import 'package:flutter/cupertino.dart';
import 'model/device_model.dart';
import 'model/group_model.dart';
import 'function.dart';
import 'dart:async';
import 'draw_record.dart';
import 'income_record.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'model/price_model.dart';
int decimal = 3;

class DevicePage extends StatefulWidget {
  @override
  _DevicePageState createState() => new _DevicePageState();
}

class _DevicePageState extends State<DevicePage> {
  _DevicePageState(){
    if(groups.length==0){
      initGroups();
    }
    if(price=="获取中"){
      initPrice();
    }

  }
  initPrice() async{
    var data =await getWkjPrice();
    price=data['current'];
    print(price);
    if(mounted){
      setState(() {});
    }
  }
  Widget indexHeader() {
    return new Container(
      color: Colors.deepOrange,
      child: new Column(
        children: <Widget>[
          new Container(
            padding: EdgeInsets.only(top: 20.0, bottom: 20.0),
            child: new Row(
              children: <Widget>[
                new Column(
                  children: <Widget>[],
                ),
                new Expanded(
                  child: new Column(
                    children: <Widget>[
                      new Text(
                        "昨日收入",
                        style: new TextStyle(color: Colors.white30, fontSize: 12.0),
                      ),
                      new Text(
                        yesterdayIncome.toStringAsFixed(decimal),
                        style: new TextStyle(color: Colors.white, fontSize: 24.0),
                      ),
                      new Text(
                        "参考价:$price",
                        style: new TextStyle(color: Colors.white, fontSize: 12.0),
                      ),
                    ],
                  ),
                ),
                new Column(
                  children: <Widget>[],
                ),
              ],
            ),
          ),
          new Container(
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new Column(
                    children: <Widget>[
                      new Text(
                        "昨日平均",
                        style: new TextStyle(
                          color: Colors.white30,
                          fontSize: 12.0,
                        ),
                      ),
                      new Text(
                        (yesterdayIncome / (deviceCount > 0 ? deviceCount : 1)).toStringAsFixed(decimal),
                        style: new TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
                new Expanded(
                  child: new Column(
                    children: <Widget>[
                      new Text(
                        "前日收入",
                        style: new TextStyle(
                          color: Colors.white30,
                          fontSize: 12.0,
                        ),
                      ),
                      new Text(
                        prevdayIncome.toStringAsFixed(decimal),
                        style: new TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
                new Expanded(
                  child: new Column(
                    children: <Widget>[
                      new Text(
                        "累计收入",
                        style: new TextStyle(
                          color: Colors.white30,
                          fontSize: 12.0,
                        ),
                      ),
                      new Text(
                        totalIncome.toStringAsFixed(decimal),
                        style: new TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
                new Expanded(
                  child: new Column(
                    children: <Widget>[
                      new Text(
                        "可提链克",
                        style: new TextStyle(
                          color: Colors.white30,
                          fontSize: 12.0,
                        ),
                      ),
                      new Text(
                        balanceIncome.toStringAsFixed(decimal),
                        style: new TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            color: new Color.fromRGBO(0, 0, 0, 0.1),
            padding: EdgeInsets.only(
              top: 10.0,
              bottom: 10.0,
            ),
          ),
        ],
      ),
    );
  }
  bool isPrivate = true;
  hideInfo(String info) {
    if (isPrivate) {
      return "test";
    } else {
      return info;
    }
  }

  List<String> groupsArray() {
    List<String> groupsArr = new List();
    groups.forEach((group) {
      groupsArr.add(group.name);
    });
    return groupsArr;
  }

  deleteDevice(DeviceModel device) {
    showDialog<Null>(
      context: context,
      builder: (context) {
        return new AlertDialog(
          title: new Text("删除确认"),
          content: new Text("确定要删除此账号吗"),
          actions: <Widget>[
            new FlatButton(
              onPressed: () {
                device.delete().then((res) {
                  if (res) {
                    toast("账号已删除");
                    for (GroupModel group in groups) {
                      if (group.id == device.group_id) {
                        group.devices.remove(device);
                      }
                    }
                    if(mounted){
                      setState(() {});
                    }
                    Navigator.pop(context);
                  } else {
                    toast("删除失败，请重试");
                  }
                });
              },
              child: new Text(
                '删除',
                style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
              ),
            ),
            new FlatButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: new Text(
                '取消',
              ),
            ),
          ],
        );
      },
    );
  }

  RefreshController _refreshController = new RefreshController();
  refreshAll(bool direction) async {
    if(direction==false){
      _refreshController.sendBack(true, RefreshStatus.refreshing);
    }else{
      for (GroupModel group in groups) {
        await refreshGroup(group);
      }
      _refreshController.sendBack(true, RefreshStatus.completed);
    }
  }

  Future<bool> refreshGroup(GroupModel group) async {
    for (DeviceModel device in group.devices) {
      await refreshDevice(device, group);
    }
    return true;
  }

  Future<bool> refreshDevice(DeviceModel device, GroupModel group) async {
    bool loginStatus = true;
    bool isLogin = await checkLogin(device.sessionid, device.userid);
    if (isLogin) {
      print("登录有效");
    } else {
      print("登录无效");
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.deviceid, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      print("开始获取账号信息");
      var accountInfo = await getAccountInfo(sessionid: device.sessionid, userid: device.userid);
      device.addr = accountInfo['addr'];
      balanceIncome =balanceIncome - device.balance_income + double.parse(accountInfo['balance']);
      device.balance_income = double.parse(accountInfo['balance']);
      print("开始获取设备信息");
      var deviceInfo = await getDeviceInfo(device.sessionid, device.userid);
      if (deviceInfo == null) {
        device.ip_addr="获取失败";
        device.province="获取";
        device.isp="失败";
      } else if (deviceInfo.length == 0) {
        device.is_bind = false;
        if(mounted){
          setState(() {});
        }
        return false;
      } else {
        print("获取设备信息成功");
        device.is_bind = true;
        device.status = deviceInfo[0]['status'];
        print(device.status);
        device.bind_time = converTime(deviceInfo[0]['bind_time']);
        device.province = deviceInfo[0]['ip_info']['province'];
        device.city = deviceInfo[0]['ip_info']['city'];
        device.isp = deviceInfo[0]['ip_info']['isp'];
        device.lan_ip = deviceInfo[0]['lan_ip'];
        device.device_name = deviceInfo[0]['device_name'];
        device.device_id = deviceInfo[0]['device_id'];
        device.device_sn = deviceInfo[0]['device_sn'];
        device.peerid = deviceInfo[0]['peerid'];
        device.ip_addr = deviceInfo[0]['ip'];
        device.hardware_model = deviceInfo[0]['hardware_model'];
        device.mac_address = deviceInfo[0]['mac_address'];
        device.system_version = deviceInfo[0]['system_version'];
        device.iswanke = deviceInfo[0]['features']['onecloud_coin'] == false ? "0" : "1";
        device.bind_days = deviceInfo[0]['features']['onecloud_coin'] == false ? "" : getTimeLong(deviceInfo[0]['features']['onecloud_coin']);
      }
      print("开始获取收入信息");
      var incomeInfo = await getIncomeRecord(sessionid: device.sessionid, userid: device.userid);
      if (incomeInfo == null) {
        print("获取收入信息失败");
      } else {
        print("获取收入信息成功");
        List incomeArr = incomeInfo['incomeArr'];
        if (incomeArr.length > 1) {
          group.yesterdayIncome = group.yesterdayIncome - device.yesterday_income + double.parse(incomeArr[0]['num']);
          group.prevdayIncome = group.prevdayIncome - device.prevday_income + double.parse(incomeArr[1]['num']);
          yesterdayIncome = yesterdayIncome - device.yesterday_income + double.parse(incomeArr[0]['num']);
          prevdayIncome = prevdayIncome - device.prevday_income + double.parse(incomeArr[1]['num']);
          totalIncome = totalIncome - device.total_income + incomeInfo['totalIncome'];

          device.total_income = incomeInfo['totalIncome'];
          device.yesterday_income = double.parse(incomeArr[0]['num']);
          device.prevday_income = double.parse(incomeArr[1]['num']);
        } else if (incomeArr.length > 0) {
          group.prevdayIncome = group.prevdayIncome - device.prevday_income + double.parse(incomeArr[1]['num']);
          yesterdayIncome = yesterdayIncome - device.yesterday_income + double.parse(incomeArr[0]['num']);
          device.yesterday_income = double.parse(incomeArr[0]['num']);
        }
      }

      print("开始获取磁盘信息");
      var usbInfo = await getUsbInfo(device.sessionid, device.userid, device.device_id);
      if (usbInfo == null) {
        print("获取磁盘信息失败");
      } else {
        device.capacity = usbInfo['capacity'];
        device.used = usbInfo['used'];
      }
      device.update();
      if(mounted){
        setState(() {});
      }
      return true;
    } else {
      return false;
    }
  }

  initGroups() async {
    var existGroups = await getGroups();
    deviceCount = await getDeviceCount();
    if (existGroups != null) {
      for (var i = 0; i < existGroups.length; i++) {
        var groupDevices = await getDevicesByGroup(existGroups[i]['id']);
        if (groupDevices != null) {
          List<DeviceModel> addDevices = [];
          groupDevices.forEach((device) {
            addDevices.add(new DeviceModel().fromMap(device));
          });
          groups.add(
            new GroupModel(id: existGroups[i]['id'], name: existGroups[i]['name'], devices: addDevices),
          );
        } else {
          groups.add(
            new GroupModel(id: existGroups[i]['id'], name: existGroups[i]['name'], devices: []),
          );
        }
      }
    } else {
      addGroup("默认分组");
      groups.add(
        new GroupModel(id: 1, name: "默认分组", devices: []),
      );
    }
    if(mounted){
      setState(() {});
    }
    refreshAll(false);

  }

  Widget _buildGroup(GroupModel group) {
    return new Container(
      child: new Column(
        children: <Widget>[
          new Container(
            decoration: new BoxDecoration(
              color: new Color(0xFFEEEEEE),
              border: new Border(
                bottom: new BorderSide(color: Colors.black12, width: 0.5),
              ),
            ),
            padding: EdgeInsets.all(5.0),
            child: new Row(
              children: <Widget>[
                new Expanded(
                  child: new Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      new Padding(
                        padding: EdgeInsets.only(right: 5.0),
                        child: new Text(
                          group.name,
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Padding(
                        padding: EdgeInsets.only(right: 5.0),
                        child: new Text(
                          group.devices.length.toString() + "台",
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Padding(
                        padding: EdgeInsets.only(right: 5.0),
                        child: new Text(
                          "昨:" + group.yesterdayIncome.toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Padding(
                        padding: EdgeInsets.only(right: 5.0),
                        child: new Text(
                          "均:" + (group.yesterdayIncome / (group.devices.length > 0 ? group.devices.length : 1)).toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ),
                      new Text(
                        "前:" + group.prevdayIncome.toStringAsFixed(decimal),
                        style: new TextStyle(
                          color: Colors.black,
                          fontSize: 12.0,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ],
                  ),
                ),
                new Padding(
                  padding: EdgeInsets.only(left: 2.5, right: 2.5),
                  child: new CupertinoButton(
                    child: new Icon(
                      Icons.refresh,
                      size: 16.0,
                    ),
                    onPressed: () {
                      refreshGroup(group);
                    },
                    padding: EdgeInsets.all(0.0),
                    minSize: 16.0,
                  ),
                ),
                new Padding(
                  padding: EdgeInsets.only(left: 2.5, right: 2.5),
                  child: new CupertinoButton(
                    child: new Icon(
                      group.showDevice ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_up,
                      size: 22.0,
                    ),
                    onPressed: () {
                      group.showDevice = !group.showDevice;
                      if(mounted){
                        setState(() {});
                      }
                    },
                    padding: EdgeInsets.all(0.0),
                    minSize: 22.0,
                  ),
                ),
              ],
            ),
          ),
          group.showDevice
              ? new Column(
                  children: group.devices.map(_buildDevice).toList(),
                )
              : new Column(),
        ],
      ),
    );
  }

  Widget _buildDevice(DeviceModel device) {
    return new Container(
      decoration: new BoxDecoration(
          border: new Border(
        bottom: BorderSide(color: Colors.black26, width: 0.5),
      )),
      child: device.is_bind == false
          ? FlatButton(
              padding: EdgeInsets.only(
                top: 10.0,
                bottom: 10.0,
              ),
              onPressed: () async {
                var device_id = "fSWRjLU_8337";
                var bindResult = await bindDevice(device.sessionid, device.userid, device_id);
              },
              child: new Row(
                children: <Widget>[
                  new Expanded(
                    child: new Column(
                      children: <Widget>[
                        new Text(
                          device.account,
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                        new Text(
                          "点击绑定设备",
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                  new CupertinoButton(
                    minSize: 22.0,
                    child: new Image.asset(
                      "images/delete.png",
                      width: 22.0,
                    ),
                    onPressed: () async {
                      deleteDevice(device);
                    },
                    padding: EdgeInsets.only(right: 5.0),
                  ),
                ],
              ),
            )
          : new FlatButton(
              padding: EdgeInsets.only(
                top: 10.0,
                bottom: 10.0,
              ),
              onPressed: () {
                showModalBottomSheet(
                    context: context,
                    builder: (ctx) {
                      return new Container(
                          child: new Column(
                        children: <Widget>[
                          new Expanded(
                            child: new ListView(
                              children: <Widget>[
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("登录账号")),
                                      new Text(device.account),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("绑定钱包")),
                                      new Text(device.addr != "" ? ("0x****" + device.addr.substring(device.addr.length - 10)) : "未绑定"),
                                      device.addr != null
                                          ? new CupertinoButton(
                                              padding: EdgeInsets.only(left: 5.0),
                                              child: new Icon(
                                                Icons.info,
                                                color: Colors.green,
                                              ),
                                              onPressed: () {},
                                              minSize: 22.0,
                                            )
                                          : new CupertinoButton(
                                              padding: EdgeInsets.only(left: 5.0),
                                              child: new Icon(
                                                Icons.info,
                                                color: Colors.green,
                                              ),
                                              onPressed: () {},
                                              minSize: 22.0,
                                            ),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("设备SN")),
                                      new Text(device.device_sn),
                                      new CupertinoButton(
                                        padding: EdgeInsets.only(left: 5.0),
                                        child: new Icon(
                                          Icons.content_copy,
                                          color: Colors.green,
                                        ),
                                        onPressed: () {},
                                        minSize: 22.0,
                                      ),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("设备ID")),
                                      new Text(device.device_id),
                                      new CupertinoButton(
                                        padding: EdgeInsets.only(left: 5.0),
                                        child: new Icon(
                                          Icons.content_copy,
                                          color: Colors.green,
                                        ),
                                        onPressed: () {},
                                        minSize: 22.0,
                                      ),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("MAC地址")),
                                      new Text(device.mac_address),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("内网IP")),
                                      new Text(device.lan_ip),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("固件版本")),
                                      new Text(device.system_version),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("设备型号")),
                                      new Text(device.hardware_model),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("绑定时间")),
                                      new Text(device.bind_time),
                                    ],
                                  ),
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new ListTile(
                                  title: new Row(
                                    children: <Widget>[
                                      new Expanded(child: Text("激活天数")),
                                      new Text(device.bind_days),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          new Container(
                            color: Colors.white,
                            child: new Column(
                              children: <Widget>[
                                new Row(
                                  children: <Widget>[
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () {},
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/unlink.png",
                                              width: 30.0,
                                            ),
                                            new Text("解除绑定"),
                                          ],
                                        ),
                                      ),
                                    ),
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () {},
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/export.png",
                                              width: 30.0,
                                            ),
                                            new Text("弹出磁盘"),
                                          ],
                                        ),
                                      ),
                                    ),
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () {},
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/reset.png",
                                              width: 30.0,
                                            ),
                                            new Text("重置设备"),
                                          ],
                                        ),
                                      ),
                                    ),
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () {
                                          Navigator.of(context).pop();
                                          deleteDevice(device);
                                        },
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/delete.png",
                                              width: 30.0,
                                            ),
                                            new Text("删除账号"),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                new Divider(
                                  height: 1.0,
                                ),
                                new Row(
                                  children: <Widget>[
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () {
                                          Navigator.of(context).push(
                                            new CupertinoPageRoute(builder: (context) {
                                              return new IncomeRecordPage(
                                                id: device.id,
                                                device_name: device.device_name,
                                              );
                                            }),
                                          );
                                        },
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/income.png",
                                              width: 30.0,
                                            ),
                                            new Text("历史收入"),
                                          ],
                                        ),
                                      ),
                                    ),
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () async {
                                          Navigator.pop(context);
                                          var isLogin = await checkLogin(device.sessionid, device.userid);
                                          bool loginStatus = true;
                                          if (!isLogin) {
                                            Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
                                            if (loginInfo != null) {
                                              print("重新登录成功");
                                              device.sessionid = loginInfo['sessionid'];
                                              device.userid = loginInfo['userid'];
                                            } else {
                                              loginStatus = false;
                                            }
                                          }
                                          if (loginStatus) {
                                            var drawResult = await applyToDraw(device.sessionid, device.userid);
                                            if (drawResult == "1") {
                                              toast("申请提币成功");
                                            } else {
                                              showDialog<Null>(
                                                context: context,
                                                builder: (context) {
                                                  return new AlertDialog(
                                                    title: new Text("提币失败"),
                                                    content: new Text(drawResult),
                                                    actions: <Widget>[
                                                      new FlatButton(
                                                        onPressed: () {
                                                          Navigator.pop(context);
                                                        },
                                                        child: new Text(
                                                          '确定',
                                                        ),
                                                      ),
                                                    ],
                                                  );
                                                },
                                              );
                                            }
                                          } else {
                                            showDialog<Null>(
                                              context: context,
                                              builder: (context) {
                                                return new AlertDialog(
                                                  title: new Text("提币失败"),
                                                  content: new Text("申请提币失败，请重试"),
                                                  actions: <Widget>[
                                                    new FlatButton(
                                                      onPressed: () async {
                                                        Navigator.of(context).pop();
                                                      },
                                                      child: new Text(
                                                        '取消',
                                                      ),
                                                    ),
                                                  ],
                                                );
                                              },
                                            );
                                          }
                                        },
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/withdraw.png",
                                              width: 30.0,
                                            ),
                                            new Text("申请提币"),
                                          ],
                                        ),
                                      ),
                                    ),
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () {
                                          Navigator.of(context).push(
                                            new CupertinoPageRoute(builder: (context) {
                                              return new DrawRecordPage(
                                                id: device.id,
                                                device_name: device.device_name,
                                              );
                                            }),
                                          );
                                        },
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/drawhistory.png",
                                              width: 30.0,
                                            ),
                                            new Text("提币记录"),
                                          ],
                                        ),
                                      ),
                                    ),
                                    new Expanded(
                                      child: new FlatButton(
                                        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
                                        onPressed: () {},
                                        child: new Column(
                                          children: <Widget>[
                                            new Image.asset(
                                              "images/download.png",
                                              width: 30.0,
                                            ),
                                            new Text("远程下载"),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ));
                    });
              },
              child: new Row(
                children: <Widget>[
                  new Expanded(
                    flex: 2,
                    child: new Column(
                      children: <Widget>[
                        new Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            new Icon(
                              Icons.brightness_1,
                              color: device.status == "online" ? Colors.green : device.status == "exception" ? Colors.red : Colors.grey,
                              size: 12.0,
                            ),
                            new Text(
                              device.device_name == "" ? "获取中" : device.device_name,
                              style: new TextStyle(
                                color: Colors.black,
                                fontSize: 12.0,
                                fontWeight: FontWeight.normal,
                              ),
                            )
                          ],
                        ),
                        new Text(
                          convertSize(device.used) + "/" + convertSize(device.capacity),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                  new Expanded(
                    flex: 2,
                    child: new Column(
                      children: <Widget>[
                        new Text(
                          "昨:" + device.yesterday_income.toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.normal,
                            fontSize: 12.0,
                          ),
                        ),
                        new Text(
                          "前:" + device.prevday_income.toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                  new Expanded(
                    flex: 2,
                    child: new Column(
                      children: <Widget>[
                        new Text(
                          "余:" + device.balance_income.toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                        new Text(
                          "总:" + device.total_income.toStringAsFixed(decimal),
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                  new Expanded(
                    flex: 3,
                    child: new Column(
                      children: <Widget>[
                        new Text(
                          device.ip_addr == null ? "获取中" : device.ip_addr,
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                        new Text(
                          (device.city == null ? device.province : device.city) + "-" + device.isp,
                          style: new TextStyle(
                            color: Colors.black,
                            fontSize: 12.0,
                            fontWeight: FontWeight.normal,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
    );
  }

  Widget _pulldownBuilder(context, mode) {
    return new ClassicIndicator(
      mode: mode,
      idleText: "继续下拉刷新",
      completeText: "刷新完成",
      refreshingText: "刷新中…",
      releaseText: "松手开始刷新",
      refreshingIcon: const CircularProgressIndicator(
        strokeWidth: 3.0,
      ),
      completeIcon: const Icon(Icons.done, size: 32.0, color: Colors.green),
    );
  }

  @override
  Widget build(BuildContext ctx) {
    return new Scaffold(
      appBar: new CupertinoNavigationBar(
        middle: new Text(
          "玩客随行",
          style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
        ),
        backgroundColor: Colors.deepOrange,
        border: new Border(bottom: BorderSide.none),
        leading: new PopupMenuButton<String>(
          tooltip: "排序",
          padding: const EdgeInsets.all(2.0),
          elevation: 2.0,
          offsetY: 60.0,
          icon: new Icon(Icons.sort_by_alpha),
          onSelected: (String value) {
            switch (value) {
              case "income_desc":
                print("收入");
                break;
              case "income_asc":
                print("收入");
                break;
              case "name_desc":
                print("提币记录");
                break;
              case "name_asc":
                print("移至分组");
                break;
              default:
                return;
            }
          },
          itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                new PopupMenuItem<String>(
                  value: 'income_desc',
                  child: new ListTile(
                    leading: new Icon(Icons.arrow_downward),
                    title: new Text("产量由高至低"),
                  ),
                ),
                new PopupMenuItem<String>(
                  value: 'income_asc',
                  child: new ListTile(
                    leading: new Icon(Icons.arrow_upward),
                    title: new Text("产量由低至高"),
                  ),
                ),
                new PopupMenuItem<String>(
                  value: 'name_desc',
                  child: new ListTile(
                    leading: new Icon(Icons.arrow_downward),
                    title: new Text("设备名Z-a"),
                  ),
                ),
                new PopupMenuItem<String>(
                  value: 'name_asc',
                  child: new ListTile(
                    leading: new Icon(Icons.arrow_upward),
                    title: new Text("设备名a-Z"),
                  ),
                ),
              ],
        ),
        trailing: new PopupMenuButton<String>(
            tooltip: "添加",
            padding: EdgeInsets.zero,
            offsetY: 60.0,
            onSelected: (value) {
              switch (value) {
                case "add_account":
                  Navigator.of(context).push(
                    new CupertinoPageRoute(builder: (context) {
                      return new AddPage(groups);
                    }),
                  ).then((value) async {
                    if (value == null) return;
                    var device = await findDeviceById(value);
                    if (device != null) {
                      for (GroupModel group in groups) {
                        if (group.id == device['group_id']) {
                          group.devices.add(new DeviceModel().fromMap(device));
                        }
                      }
                      if(mounted){
                        setState(() {});
                      }
                    } else {
                      toast("添加出错，请重试");
                    }
                  });
                  break;
                case "import_export":
                  Navigator.of(context).push(
                    new CupertinoPageRoute(builder: (context) {
                      return new LoginPage();
                    }),
                  );
                  break;
                case "add_group":
                  showDialog<Null>(
                    context: ctx,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("添加分组"),
                        content: new Container(
                            height: 75.0,
                            child: new Column(
                              children: <Widget>[
                                new TextField(
                                  decoration: new InputDecoration(
                                    hintText: '请输入分组名',
                                    labelText: "分组名",
                                  ),
                                  onChanged: (value) {
                                    addGroupName = value;
                                  },
                                ),
                              ],
                            )),
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: new Text(
                              '取消',
                            ),
                          ),
                          new FlatButton(
                            onPressed: () async {
                              if (addGroupName == "") {
                                toast("请输入分组名");
                                return null;
                              }
                              var addRes = await addGroup(addGroupName);
                              groups.add(
                                new GroupModel(id: addRes, name: addGroupName, devices: []),
                              );
                              addGroupName = "";
                              if (addRes != null) {
                                toast("添加分组成功");
                              }
                              if(mounted){
                                setState(() {});
                              }
                            },
                            child: new Text(
                              '添加',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      );
                    },
                  );
                  break;
              }
            },
            icon: Icon(Icons.add),
            itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                  const PopupMenuItem<String>(value: 'add_account', child: const ListTile(leading: const Icon(Icons.person_add), title: const Text('添加账号'))),
                  const PopupMenuItem<String>(value: 'import_export', child: const ListTile(leading: const Icon(Icons.import_export), title: const Text('导入导出'))),
                  const PopupMenuDivider(), // ignore: list_element_type_not_assignable, https://github.com/flutter/flutter/issues/5771
                  const PopupMenuItem<String>(value: 'add_group', child: const ListTile(leading: const Icon(Icons.add_circle_outline), title: const Text('添加分组')))
                ]),
        actionsForegroundColor: Colors.white,
      ),
      body: new Container(
        color: Colors.white,
        child: new SafeArea(
          child: new Column(
            children: <Widget>[
              indexHeader(),
              new Expanded(
                child: new SmartRefresher(
                  enablePullDown: true,
                  onRefresh: refreshAll,
                  headerBuilder: _pulldownBuilder,
                  controller: _refreshController,
                  child: new ListView.builder(
                    itemCount: groups.length,
                    itemBuilder: (context, i) => _buildGroup(groups[i]),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
